package net.kong.yumo.utils;

import java.net.URL;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
 * Ehcache 工具类
 * 使用  static EhcacheUtil  对创建的 CacheManager 操作
 * 
 * @author king
 *
 */
public class EhcacheUtil {

	private static final String path = "ehcache.xml";
	

	private CacheManager manager;
	private URL url;  

	private static EhcacheUtil ehCache;
	
	public String cacheName="datawayCache";

	private EhcacheUtil(String path) {
		url = getClass().getResource(path);
		manager = CacheManager.create(url);
	}

	public static EhcacheUtil getInstance() {
		if (ehCache== null) {
			ehCache= new EhcacheUtil(path);
		}
		return ehCache;
	}
	
	public void setEhcache(String cheName , String key , Object value) {
		Cache cache = manager.getCache(cheName);
		this.cacheName = cheName;
		if(cache == null){
			cache = new Cache( cheName ,100000, true , true , 0 , 0 );
			manager.addCache(cache);
		}
		cache.put(new Element(key, value));
		cache.flush();
	}
	
	public void setEhcache(String key , Object value){
		Cache cache = manager.getCache(cacheName);
		if(cache == null){
			cache = new Cache( cacheName ,100000, true , true , 0 , 0 );
			manager.addCache(cache);
		}
		cache.put(new Element(key, value));
		cache.flush();
	}
	
	public Object getEhcache(String key) {
        Cache cache1 = manager.getCache( cacheName );
        Element element = cache1.get(key);
        return element.getValue();
    }
	 
	public Object getEhcache(String cachName , String key) {
		Cache cache = manager.getCache( cachName );
		Element element = cache.get(key);
		return element.getValue();
	}
	
	public Cache get(String cacheName) {
		return manager.getCache(cacheName);
	}
	
	public void remove(String cacheName, String key) {
		Cache cache = manager.getCache(cacheName);
		cache.remove(key);
		cache.flush();
	}
	
	public void remove(String key) {
		Cache cache = manager.getCache(cacheName);
		cache.remove(key);
		cache.flush();
	}


}

